<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>组织颜色图谱检测工具</title>
    <!-- Chart.js for visualization，使用 cdnjs 加载 -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.0/chart.umd.js"></script>
    <!-- html2canvas for PDF generation -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <style>
        :root {
            --color-red: #FF4444;
            --color-amber: #FFD700;
            --color-orange: #FFA500;
            --color-teal: #00CED1;
            --color-background: #f9fafb;
            --color-text: #1f2937;
            --color-card: white;
            --color-primary: #3b82f6;
            --color-primary-hover: #2563eb;
            --color-secondary: #10b981;
            --color-secondary-hover: #059669;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: var(--color-text);
            background-color: var(--color-background);
            padding: 0;
            margin: 0;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }

        header {
            text-align: center;
            margin-bottom: 2rem;
        }

        h1 {
            font-size: 2.5rem;
            margin-bottom: 0.5rem;
            color: var(--color-text);
        }

        h2 {
            font-size: 1.8rem;
            margin: 1.5rem 0 1rem;
            color: var(--color-text);
            border-bottom: 2px solid var(--color-primary);
            padding-bottom: 0.5rem;
        }

        .card {
            background-color: var(--color-card);
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .question {
            margin-bottom: 1.5rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #e5e7eb;
        }

        .question:last-child {
            border-bottom: none;
        }

        .question-text {
            font-weight: 600;
            margin-bottom: 0.75rem;
        }

        .option {
            display: flex;
            align-items: center;
            margin-bottom: 0.5rem;
            padding: 0.5rem;
            border-radius: 0.25rem;
            transition: background-color 0.2s;
        }

        .option:hover {
            background-color: rgba(0, 0, 0, 0.05);
        }

        .option input {
            margin-right: 0.75rem;
        }

        button {
            background-color: var(--color-primary);
            color: white;
            border: none;
            border-radius: 0.375rem;
            padding: 0.75rem 1.5rem;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.2s;
        }

        button:hover {
            background-color: var(--color-primary-hover);
        }

        button:disabled {
            background-color: #9ca3af;
            cursor: not-allowed;
        }

        .btn-secondary {
            background-color: var(--color-secondary);
        }

        .btn-secondary:hover {
            background-color: var(--color-secondary-hover);
        }

        .actions {
            display: flex;
            gap: 1rem;
            margin-top: 1.5rem;
        }

        .results-container {
            display: none;
            margin-top: 2rem;
        }

        .chart-container {
            height: 400px;
            margin: 2rem 0;
        }

        .advice-container {
            background-color: var(--color-card);
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            padding: 1.5rem;
            margin-top: 1.5rem;
        }

        .advice-title {
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }

        .advice-list {
            padding-left: 1.5rem;
        }

        .risk-container {
            margin-top: 1rem;
            padding: 0.75rem;
            background-color: #fee2e2;
            border-radius: 0.375rem;
            border-left: 4px solid var(--color-red);
        }

        .dimensions-container {
            display: flex;
            flex-wrap: wrap;
            gap: 1.5rem;
        }

        .dimension-card {
            flex: 1 1 calc(50% - 1.5rem);
            min-width: 300px;
        }

        @media (max-width: 768px) {
            .dimension-card {
                flex: 1 1 100%;
            }
        }

        .color-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 6px;
        }

        .legend {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin: 1rem 0;
        }

        .legend-item {
            display: flex;
            align-items: center;
        }

        .progress-indicator {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background-color: var(--color-card);
            padding: 10px 15px;
            border-radius: 20px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            gap: 8px;
            z-index: 1000;
        }

        .progress-text {
            font-weight: bold;
        }

        .pdf-content {
            display: none;
            background-color: white;
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }

        .pdf-content h2 {
            font-size: 24px;
            margin-bottom: 20px;
        }

        .pdf-content table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }

        .pdf-content th, .pdf-content td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        .pdf-content th {
            background-color: #2980b9;
            color: white;
        }

        .pdf-content ul {
            padding-left: 20px;
        }

        .pdf-content .risk {
            margin-top: 15px;
            padding: 10px;
            background-color: #fee2e2;
            border-left: 4px solid var(--color-red);
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>组织颜色图谱检测工具</h1>
            <p>完成下方问卷，获取您的组织颜色图谱分析</p>
        </header>

        <div id="questionnaire-container">
            <div class="dimensions-container" id="dimensions-container">
                <!-- Dimensions will be generated here -->
            </div>

            <div class="actions">
                <button id="view-results-btn" disabled>查看结果</button>
            </div>
        </div>

        <div id="results-container" class="results-container">
            <h2>颜色图谱分析结果</h2>
            
            <div class="legend">
                <div class="legend-item">
                    <span class="color-indicator" style="background-color: var(--color-red);"></span>
                    <span>红色 (控制型)</span>
                </div>
                <div class="legend-item">
                    <span class="color-indicator" style="background-color: var(--color-amber);"></span>
                    <span>琥珀色 (规则型)</span>
                </div>
                <div class="legend-item">
                    <span class="color-indicator" style="background-color: var(--color-orange);"></span>
                    <span>橙色 (绩效型)</span>
                </div>
                <div class="legend-item">
                    <span class="color-indicator" style="background-color: var(--color-teal);"></span>
                    <span>蓝绿色 (进化型)</span>
                </div>
            </div>
            
            <div class="chart-container">
                <canvas id="results-chart"></canvas>
            </div>
            
            <div class="advice-container">
                <h3 id="org-portrait"></h3>
                <div class="advice-title">改进建议:</div>
                <ul id="advice-list" class="advice-list"></ul>
                <div id="risk-container" class="risk-container">
                    <div class="advice-title">风险提示:</div>
                    <div id="risk-text"></div>
                </div>
            </div>
            
            <div class="actions">
                <button id="generate-pdf-btn" class="btn-secondary">生成 PDF 诊断报告</button>
                <button id="restart-btn">重新测试</button>
            </div>
        </div>

        <div id="progress-indicator" class="progress-indicator">
            <span class="progress-text">已完成: </span>
            <span id="progress-percentage">0%</span>
        </div>
    </div>

    <script>
        // Constants
        const COLORS = ['#FF4444', '#FFD700', '#FFA500', '#00CED1'];
        const COLOR_NAMES = ['red', 'amber', 'orange', 'teal'];
        const DIMENSIONS = [
            {
                name: '决策控制',
                weight: 0.3,
                questions: [
                    {
                        id: 'Q01',
                        text: '新产品研发的最终决策权归属？',
                        options: [
                            { text: 'CEO直接决定', color: 'red', score: 5 },
                            { text: '市场部负责人审批', color: 'orange', score: 3 },
                            { text: '跨职能团队共识', color: 'teal', score: 7 },
                        ],
                    },
                    {
                        id: 'Q02',
                        text: '部门预算调整的审批流程层级？',
                        options: [
                            { text: '3级及以上', color: 'red', score: 4 },
                            { text: '2级审批', color: 'amber', score: 2 },
                            { text: '自主决定', color: 'teal', score: 6 },
                        ],
                    },
                    {
                        id: 'Q03',
                        text: '突发危机的应急决策速度？',
                        options: [
                            { text: '需层层上报', color: 'red', score: 5 },
                            { text: '预案自动执行', color: 'orange', score: 4 },
                            { text: '一线团队自主响应', color: 'teal', score: 8 },
                        ],
                    },
                    {
                        id: 'Q04',
                        text: '员工晋升的决定依据？',
                        options: [
                            { text: '上级主观评价', color: 'red', score: 3 },
                            { text: '绩效考核系统', color: 'orange', score: 5 },
                            { text: '同事互评+自荐', color: 'teal', score: 7 },
                        ],
                    },
                    {
                        id: 'Q05',
                        text: '战略目标调整的频率？',
                        options: [
                            { text: '五年规划', color: 'amber', score: 5 },
                            { text: '年度调整', color: 'orange', score: 3 },
                            { text: '季度迭代', color: 'teal', score: 6 },
                        ],
                    },
                ],
            },
            {
                name: '信息传播',
                weight: 0.25,
                questions: [
                    {
                        id: 'Q06',
                        text: '财务报表的开放范围？',
                        options: [
                            { text: '仅董事会', color: 'red', score: 5 },
                            { text: '中层以上', color: 'orange', score: 3 },
                            { text: '全员可见', color: 'teal', score: 7 },
                        ],
                    },
                    {
                        id: 'Q07',
                        text: '会议信息的记录与共享方式？',
                        options: [
                            { text: '保密存档', color: 'red', score: 4 },
                            { text: '邮件通报', color: 'amber', score: 3 },
                            { text: '实时云端共享', color: 'teal', score: 6 },
                        ],
                    },
                    {
                        id: 'Q08',
                        text: '市场情报的获取渠道？',
                        options: [
                            { text: '高管人脉', color: 'red', score: 5 },
                            { text: '商业数据库', color: 'orange', score: 4 },
                            { text: '全员信息雷达', color: 'teal', score: 8 },
                        ],
                    },
                    {
                        id: 'Q09',
                        text: '员工建议的反馈周期？',
                        options: [
                            { text: '无固定流程', color: 'red', score: 3 },
                            { text: '季度收集', color: 'amber', score: 2 },
                            { text: '即时讨论实施', color: 'teal', score: 7 },
                        ],
                    },
                    {
                        id: 'Q10',
                        text: '跨部门协作的信息同步方式？',
                        options: [
                            { text: '逐级传递', color: 'red', score: 4 },
                            { text: '企业微信通知', color: 'orange', score: 3 },
                            { text: '共享看板实时更新', color: 'teal', score: 6 },
                        ],
                    },
                ],
            },
            {
                name: '文化构建',
                weight: 0.25,
                questions: [
                    {
                        id: 'Q11',
                        text: '新员工适应期引导方式？',
                        options: [
                            { text: '规章制度培训', color: 'red', score: 3 },
                            { text: '导师制度', color: 'orange', score: 4 },
                            { text: '自组织学习圈', color: 'teal', score: 7 },
                        ],
                    },
                    {
                        id: 'Q12',
                        text: '价值观渗透的主要途径？',
                        options: [
                            { text: '标语考核', color: 'red', score: 4 },
                            { text: '案例教学', color: 'orange', score: 3 },
                            { text: '日常实践共识', color: 'teal', score: 6 },
                        ],
                    },
                    {
                        id: 'Q13',
                        text: '创新失败的后续处理？',
                        options: [
                            { text: '追责处罚', color: 'red', score: 5 },
                            { text: '流程优化', color: 'orange', score: 4 },
                            { text: '庆功分享', color: 'teal', score: 8 },
                        ],
                    },
                    {
                        id: 'Q14',
                        text: '会议中的不同意见表达？',
                        options: [
                            { text: '禁止公开质疑', color: 'red', score: 5 },
                            { text: '事后单独反馈', color: 'amber', score: 3 },
                            { text: '即时开放讨论', color: 'teal', score: 7 },
                        ],
                    },
                    {
                        id: 'Q15',
                        text: '员工职业发展支持方式？',
                        options: [
                            { text: '统一培训计划', color: 'amber', score: 4 },
                            { text: '在线学习平台', color: 'orange', score: 3 },
                            { text: '自主成长基金', color: 'teal', score: 6 },
                        ],
                    },
                ],
            },
            {
                name: '系统演化',
                weight: 0.2,
                questions: [
                    {
                        id: 'Q16',
                        text: '组织架构调整的触发条件？',
                        options: [
                            { text: '领导换届', color: 'red', score: 5 },
                            { text: '战略周期', color: 'orange', score: 3 },
                            { text: '环境实时响应', color: 'teal', score: 7 },
                        ],
                    },
                    {
                        id: 'Q17',
                        text: '供应商合作的信息共享程度？',
                        options: [
                            { text: '数据隔离', color: 'red', score: 4 },
                            { text: '系统对接', color: 'orange', score: 3 },
                            { text: '生态信息池', color: 'teal', score: 6 },
                        ],
                    },
                    {
                        id: 'Q18',
                        text: '外部环境感知的主要方式？',
                        options: [
                            { text: '高管直觉', color: 'red', score: 5 },
                            { text: '行业报告', color: 'orange', score: 4 },
                            { text: '全员感知网络', color: 'teal', score: 8 },
                        ],
                    },
                    {
                        id: 'Q19',
                        text: '新业务试错的资源支持？',
                        options: [
                            { text: '严格审批', color: 'red', score: 3 },
                            { text: '预算限额', color: 'amber', score: 2 },
                            { text: '自主创新基金', color: 'teal', score: 7 },
                        ],
                    },
                    {
                        id: 'Q20',
                        text: '绩效考核的核心指标类型？',
                        options: [
                            { text: '服从度', color: 'red', score: 4 },
                            { text: 'KPI完成率', color: 'orange', score: 5 },
                            { text: '价值创造贡献度', color: 'teal', score: 6 },
                        ],
                    },
                ],
            },
        ];

        const ADVICE_MATRIX = {
            'red+amber': {
                portrait: '强人治下的官僚体系',
                advice: [
                    '建立「红转橙」过渡机制：在财务/HR部门试点OKR+KPI混合考核',
                    '植入「流程破壁者」角色：选拔3%员工担任制度冗余检测员',
                    '启动「去审批化」实验：将20%常规决策权下沉至一线',
                ],
                risk: '可能遭遇中层管理者集体抵制',
            },
            'red+orange': {
                portrait: '军事化管理的狼性团队',
                advice: [
                    '设计「双轨决策系统」：保留战略层集权，业务层实施合弄制',
                    '构建「创新隔离区」：设立无需KPI考核的20%自由实验资源',
                    '实施「透明化三步走」：先开放客户数据→运营数据→财务数据',
                ],
                risk: '过度强调绩效可能加速人才流失',
            },
            'amber+orange': {
                portrait: '精密运行的商业机器',
                advice: [
                    '启动「规则代谢计划」：每年淘汰15%陈旧制度',
                    '建立「流程弹性指数」：用API接口替代30%纸质审批',
                    '推行「价值观KPI」：将员工协作度纳入20%考核权重',
                ],
                risk: '可能导致短期效率下降5-8%',
            },
            'orange+teal': {
                portrait: '自我驱动的创新组织',
                advice: [
                    '设计「动态目标网络」：用OKR系统连接跨部门目标节点',
                    '实施「细胞分裂机制」：当团队超过15人时强制拆分新单元',
                    '开放「战略沙盒」：允许10%资源用于员工自驱项目',
                ],
                risk: '需预防目标碎片化风险',
            },
            'teal+red': {
                portrait: '理想主义与强权博弈场',
                advice: [
                    '创建「双模式操作系统」：传统业务线保持层级制，新业务线全面自治',
                    '实施「权力透明化」：公示高管决策影响因子分布图',
                    '启动「价值观对齐度」季度评估',
                ],
                risk: '可能产生文化认知分裂',
            },
            'amber+teal': {
                portrait: '戴着镣铐跳舞的创新者',
                advice: [
                    '构建「最小可行规则集」：将制度文档压缩至50页以内',
                    '开发「规则众改平台」：员工可标注制度痛点并提交修正案',
                    '实施「静默会议」实验：每月1天禁止邮件/审批/汇报',
                ],
                risk: '需防范无政府主义倾向',
            },
            red: {
                portrait: '控制型单极组织',
                advice: [
                    '建立「红转橙」过渡机制：在财务/HR部门试点OKR+KPI混合考核',
                    '植入「流程破壁者」角色：选拔3%员工担任制度冗余检测员',
                    '启动「去审批化」实验：将20%常规决策权下沉至一线',
                ],
                risk: '可能遭遇中层管理者集体抵制',
            },
            amber: {
                portrait: '规则型单极组织',
                advice: [
                    '启动「规则代谢计划」：每年淘汰15%陈旧制度',
                    '建立「流程弹性指数」：用API接口替代30%纸质审批',
                    '推行「价值观KPI」：将员工协作度纳入20%考核权重',
                ],
                risk: '可能导致短期效率下降5-8%',
            },
            orange: {
                portrait: '绩效型单极组织',
                advice: [
                    '设计「双轨决策系统」：保留战略层集权，业务层实施合弄制',
                    '构建「创新隔离区」：设立无需KPI考核的20%自由实验资源',
                    '实施「透明化三步走」：先开放客户数据→运营数据→财务数据',
                ],
                risk: '过度强调绩效可能加速人才流失',
            },
            teal: {
                portrait: '进化型单极组织',
                advice: [
                    '建立「反脆弱架构」：通过冗余设计预防过度扁平化风险',
                    '启动「生态系统计划」：与上下游伙伴共享战略信息池',
                    '实施「组织冥想日」：季度性暂停所有运营活动进行系统反思',
                ],
                risk: '有效自组织需要高成熟度人才',
            },
        };

        // Variables
        let answers = {};
        let chart = null;

        // DOM Elements
        const dimensionsContainer = document.getElementById('dimensions-container');
        const resultsContainer = document.getElementById('results-container');
        const viewResultsBtn = document.getElementById('view-results-btn');
        const generatePdfBtn = document.getElementById('generate-pdf-btn');
        const restartBtn = document.getElementById('restart-btn');
        const progressPercentage = document.getElementById('progress-percentage');
        const orgPortrait = document.getElementById('org-portrait');
        const adviceList = document.getElementById('advice-list');
        const riskText = document.getElementById('risk-text');

        // Initialize
        function init() {
            renderQuestions();
            setupEventListeners();
            updateProgress();
        }

        // Render all questions
        function renderQuestions() {
            dimensionsContainer.innerHTML = '';
            
            // 创建一个 DocumentFragment
            const fragment = document.createDocumentFragment();
            
            DIMENSIONS.forEach((dimension) => {
                const dimensionCard = document.createElement('div');
                dimensionCard.className = 'dimension-card card';
                
                const dimensionTitle = document.createElement('h2');
                // 修改此处，只显示维度名称
                dimensionTitle.textContent = `${dimension.name}维度`;
                dimensionCard.appendChild(dimensionTitle);
                
                dimension.questions.forEach((question) => {
                    const questionDiv = document.createElement('div');
                    questionDiv.className = 'question';
                    
                    const questionText = document.createElement('p');
                    questionText.className = 'question-text';
                    questionText.textContent = question.text;
                    questionDiv.appendChild(questionText);
                    
                    question.options.forEach((option, index) => {
                        const optionDiv = document.createElement('div');
                        optionDiv.className = 'option';
                        optionDiv.style.cursor = 'pointer'; // 添加鼠标指针样式
                        
                        const radio = document.createElement('input');
                        radio.type = 'radio';
                        radio.name = question.id;
                        radio.value = index;
                        radio.id = `${question.id}-${index}`;
                        
                        const label = document.createElement('label');
                        label.htmlFor = `${question.id}-${index}`;
                        label.textContent = option.text;
                        
                        optionDiv.appendChild(radio);
                        optionDiv.appendChild(label);
                        questionDiv.appendChild(optionDiv);

                        // 为整个选项 div 绑定点击事件
                        optionDiv.addEventListener('click', () => {
                            radio.checked = true;
                            handleAnswerChange(question.id, index);
                        });
                    });
                    
                    dimensionCard.appendChild(questionDiv);
                });
                // 将 dimensionCard 添加到 DocumentFragment 中
                fragment.appendChild(dimensionCard);
            });
            // 一次性将 DocumentFragment 插入到文档中
            dimensionsContainer.appendChild(fragment);
        }

        // Setup event listeners
        function setupEventListeners() {
            viewResultsBtn.addEventListener('click', handleViewResults);
            generatePdfBtn.addEventListener('click', generatePDF);
            restartBtn.addEventListener('click', handleRestart);
        }

        // Handle answer change
        function handleAnswerChange(questionId, optionIndex) {
            answers[questionId] = optionIndex;
            updateProgress();
        }

        // Update progress indicator
        function updateProgress() {
            const totalQuestions = DIMENSIONS.reduce((total, dimension) => total + dimension.questions.length, 0);
            const answeredQuestions = Object.keys(answers).length;
            const percentage = Math.round((answeredQuestions / totalQuestions) * 100);
            
            progressPercentage.textContent = `${percentage}%`;
            
            if (percentage >= 100) {
                viewResultsBtn.disabled = false;
            } else {
                viewResultsBtn.disabled = true;
            }
        }

        // Handle view results
        function handleViewResults() {
            const totalQuestions = DIMENSIONS.reduce((total, dimension) => total + dimension.questions.length, 0);
            const answeredQuestions = Object.keys(answers).length;
            
            if (answeredQuestions < totalQuestions) {
                alert(`请完成所有问题（${answeredQuestions}/${totalQuestions}）`);
                return;
            }
            
            resultsContainer.style.display = 'block';
            resultsContainer.scrollIntoView({ behavior: 'smooth' });
            
            renderResults();
        }

        // Calculate scores
        function calculateScores() {
            const scores = { red: 0, amber: 0, orange: 0, teal: 0 };
            
            DIMENSIONS.forEach((dimension) => {
                dimension.questions.forEach((question) => {
                    const answerIndex = answers[question.id];
                    if (answerIndex !== undefined) {
                        const option = question.options[answerIndex];
                        scores[option.color] += option.score * dimension.weight;
                    }
                });
            });
            
            const totalScore = Object.values(scores).reduce((acc, score) => acc + score, 0);
            
            const percentages = {};
            for (const [color, score] of Object.entries(scores)) {
                percentages[color] = parseFloat(((score / totalScore) * 100).toFixed(2));
            }
            
            return percentages;
        }

        // Generate advice
        function generateAdvice(percentages) {
            const sortedColors = Object.entries(percentages)
                .sort((a, b) => b[1] - a[1])
                .map(([color]) => color);
                
            const topColor = sortedColors[0];
            const secondColor = sortedColors[1];
            
            if (percentages[topColor] > 50) {
                return ADVICE_MATRIX[topColor];
            }
            
            const key = `${topColor}+${secondColor}`;
            return ADVICE_MATRIX[key] || ADVICE_MATRIX[topColor];
        }

        // Render results
        function renderResults() {
            const percentages = calculateScores();
            const advice = generateAdvice(percentages);
            
            // Render chart
            renderChart(percentages);
            
            // Render advice
            orgPortrait.textContent = `组织画像: ${advice.portrait}`;
            
            adviceList.innerHTML = '';
            advice.advice.forEach((item) => {
                const li = document.createElement('li');
                li.textContent = item;
                adviceList.appendChild(li);
            });
            
            riskText.textContent = advice.risk;
        }

        // Render chart
        function renderChart(percentages) {
            const ctx = document.getElementById('results-chart').getContext('2d');
            
            if (chart) {
                chart.destroy();
            }
            
            chart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['红色 (控制型)', '琥珀色 (规则型)', '橙色 (绩效型)', '蓝绿色 (进化型)'],
                    datasets: [{
                        data: [
                            percentages.red,
                            percentages.amber,
                            percentages.orange,
                            percentages.teal
                        ],
                        backgroundColor: COLORS,
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `${context.label}: ${context.parsed}%`;
                                }
                            }
                        }
                    }
                }
            });
        }

        // Generate PDF using html2canvas
        function generatePDF() {
            try {
                const percentages = calculateScores();
                const advice = generateAdvice(percentages);
                
                // Create the PDF content in DOM first
                const pdfContent = document.createElement('div');
                pdfContent.className = 'pdf-content';
                document.body.appendChild(pdfContent);
                
                // Add title
                const title = document.createElement('h2');
                title.innerText = '组织颜色图谱检测报告';
                pdfContent.appendChild(title);
                
                // Add color distribution
                const distTitle = document.createElement('h3');
                distTitle.innerText = '颜色图谱分布:';
                pdfContent.appendChild(distTitle);
                
                // Create table
                const table = document.createElement('table');
                const thead = document.createElement('thead');
                const tbody = document.createElement('tbody');
                
                // Add table header
                const headerRow = document.createElement('tr');
                const th1 = document.createElement('th');
                th1.innerText = '颜色';
                const th2 = document.createElement('th');
                th2.innerText = '占比';
                headerRow.appendChild(th1);
                headerRow.appendChild(th2);
                thead.appendChild(headerRow);
                table.appendChild(thead);
                
                // Add table rows
                const colors = [
                    { name: '红色 (控制型)', value: percentages.red },
                    { name: '琥珀色 (规则型)', value: percentages.amber },
                    { name: '橙色 (绩效型)', value: percentages.orange },
                    { name: '蓝绿色 (进化型)', value: percentages.teal }
                ];
                
                colors.forEach(color => {
                    const row = document.createElement('tr');
                    const td1 = document.createElement('td');
                    td1.innerText = color.name;
                    const td2 = document.createElement('td');
                    td2.innerText = `${color.value}%`;
                    row.appendChild(td1);
                    row.appendChild(td2);
                    tbody.appendChild(row);
                });
                
                table.appendChild(tbody);
                pdfContent.appendChild(table);
                
                // Add organization portrait
                const portrait = document.createElement('h3');
                portrait.innerText = `组织画像: ${advice.portrait}`;
                pdfContent.appendChild(portrait);
                
                // Add advice
                const adviceTitle = document.createElement('h3');
                adviceTitle.innerText = '改进建议:';
                pdfContent.appendChild(adviceTitle);
                
                const adviceList = document.createElement('ul');
                advice.advice.forEach(item => {
                    const li = document.createElement('li');
                    li.innerText = item;
                    adviceList.appendChild(li);
                });
                pdfContent.appendChild(adviceList);
                
                // Add risk
                const riskDiv = document.createElement('div');
                riskDiv.className = 'risk';
                const riskTitle = document.createElement('h4');
                riskTitle.innerText = '风险提示:';
                const riskText = document.createElement('p');
                riskText.innerText = advice.risk;
                riskDiv.appendChild(riskTitle);
                riskDiv.appendChild(riskText);
                pdfContent.appendChild(riskDiv);
                
                // Apply default styles to the PDF content for better rendering
                pdfContent.style.display = 'block';
                
                // Use html2canvas to convert the content to an image
                html2canvas(pdfContent).then(canvas => {
                    const imgData = canvas.toDataURL('image/png');
                    const { jsPDF } = window.jspdf;
                    const pdf = new jsPDF('p', 'mm', 'a4');
                    
                    // Calculate dimensions
                    const imgWidth = 210; // A4 width in mm
                    const pageHeight = 295; // A4 height in mm
                    const imgHeight = canvas.height * imgWidth / canvas.width;
                    
                    pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
                    
                    // Save PDF
                    pdf.save('组织颜色图谱检测报告.pdf');
                    
                    // Clean up
                    document.body.removeChild(pdfContent);
                });
            } catch (error) {
                console.error("PDF生成错误:", error);
                alert("生成PDF时出错，请查看控制台以获取详细信息。");
            }
        }

        // Handle restart
        function handleRestart() {
            answers = {};
            resultsContainer.style.display = 'none';
            updateProgress();
            
            // Uncheck all radios
            const radios = document.querySelectorAll('input[type="radio"]');
            radios.forEach(radio => radio.checked = false);
            
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

        // Initialize the app
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>